package com.ruoyi.recycle.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

public class MiniProgramUtil {

    public static String getToken(String appid,String secret) {
        try {
            Map<String, String> map = new LinkedHashMap<String, String>();
            map.put("grant_type", "client_credential");
            //综合站：wxc1c3b06bb75f14ba     客户端：wxc097c5dcf8c9cf16
            map.put("appid", appid);// 改成自己的appid
            //综合站：527fb7eeaeb4be2e6fa7612825289f68  客户端：f75025b2e55941f579ef625e1dc4886f
            map.put("secret", secret); //改成自己的secret
            String rt = UrlUtil.sendPost("https://api.weixin.qq.com/cgi-bin/token", map);
            JSONObject json = JSONObject.parseObject(rt);
            if (json.getString("access_token") != null || json.getString("access_token") != "") {
                System.out.println("token:" + json.getString("access_token"));
                return json.getString("access_token");
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 生成带参小程序二维码
     *
     * @param accessToken token
     */
    public static String postMiniqrQr(String scene, String path, String accessToken) {
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true); // 打开写入属性
            httpURLConnection.setDoInput(true); // 打开读取属性
            httpURLConnection.setRequestMethod("POST");// 提交方式
            // 不得不说一下这个提交方式转换！！真的坑。。改了好长时间！！一定要记得加响应头
            httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");// 设置响应头
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            System.out.println("path = " + path);
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene); // 你要放的内容
            paramJson.put("page", path);
            paramJson.put("width", 430); // 宽度
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            //创建一个空文件
            //OutputStream os = new FileOutputStream(new File("D:\\java\\小项目\\tu\\test.png"));
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }

            final ByteArrayInputStream swapStream = new ByteArrayInputStream(os.toByteArray());
            // 上传云储存
            MultipartFile file = new MockMultipartFile(UUID.randomUUID().toString(), swapStream);
            String sux = ".png";
            String codeAddress = OssUpload.uploadFile(file, sux);

            os.close();
            return codeAddress;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("生成小程序码异常 = " + e);
            return "服务器出小差了";
        }
    }

    public static void main(String[] args) {
        String token = getToken("wxc1c3b06bb75f14ba","527fb7eeaeb4be2e6fa7612825289f68");

        String miniqr = postMiniqrQr("id=1,type=4", "pages/index/index", token);
        System.out.println("小程序码 = " + miniqr);

    }


}
